package com.gouaixin.bee.beeframework2.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListener;
import com.ab.util.AbDialogUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.activity.B2_fensiActivity;
import com.gouaixin.bee.beeframework2.activity.B3_fangkeActivity;
import com.gouaixin.bee.beeframework2.activity.B3_zhenxinhuaFriendActivity;
import com.gouaixin.bee.beeframework2.activity.C2_MsgActivity;
import com.gouaixin.bee.beeframework2.activity.C2_ServiceMsgActivity;
import com.gouaixin.bee.beeframework2.activity.MyMainActivity;
import com.gouaixin.bee.beeframework2.adapter.MailAdapter;
import com.gouaixin.bee.beeframework2.bean.getChatFriendsResponse;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.XHttpUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;

/**
 * Created by Administrator on 2015/3/6.
 */
public class M2_mailFragment extends Fragment implements AdapterView.OnItemClickListener {


    View mainView;

    ListView list;
    MailAdapter mMailAdapter;

    public  ArrayList<getChatFriendsResponse> datas = new ArrayList<getChatFriendsResponse>();

    String cid="";
    String cname="";
    String jid="";
    String jicon="";


    /**
     *  在这里实现Fragment数据的缓加载.    
     */
    public boolean isVisible;

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    public  void onVisible() {

        getChatFriends();

    }


    public void onInvisible() {
    }

    /***
     * 设置底部信箱的数字
     * 1.遍历集合，获取每个元素
     * 2.得到每个元素的信箱数字
     * 3.求和
     */
    public  void setMailNumber(){
        int num=0;
        if(datas!=null){
            for(int i=0;i<datas.size();i++){
                getChatFriendsResponse bean=datas.get(i);
                String jid=bean.getId();
                int temp= PreferencesUtils.getInt(getActivity(), jid + "MailNumber", 0);
//                mLog.e(jid + "MailNumber="+temp);
                num+=temp;
            }
        }

        int fangkeNumber= PreferencesUtils.getInt(getActivity(), cid + "Fangke", 0);
        int guanzhuNumber= PreferencesUtils.getInt(getActivity(), cid + "Guanzhu", 0);
        int ZhenxinhuaFriendNumber= PreferencesUtils.getInt(getActivity(), cid + "ZhenxinhuaFriend", 0);
        int MishuMsgNumber= PreferencesUtils.getInt(getActivity(), "MishuMsg", 0);
        num=num+fangkeNumber+guanzhuNumber+ZhenxinhuaFriendNumber+MishuMsgNumber;

        if(num==0){
            MyMainActivity.mail_num_bg.setVisibility(View.GONE);
        }else {
            MyMainActivity.mail_num_bg.setVisibility(View.VISIBLE);
            MyMainActivity.mail_num.setText(num+"");
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        mainView = inflater.inflate(R.layout.m2_mail, null);


        initReceiver();

        initView();


        initPullToRefresh();


        initContent();


        return mainView;
    }

    //注册一个广播接收器，实时刷新消息列表
    private void initReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("action.refreshFriend");
        getActivity().registerReceiver(mRefreshBroadcastReceiver, intentFilter);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出时销毁广播接收器
        getActivity().unregisterReceiver(mRefreshBroadcastReceiver);
    }

    // broadcast receiver
    private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.refreshFriend"))
            {
                getChatFriends();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();

        getChatFriends();
    }

    private void initView() {
        list = (ListView) mainView.findViewById(R.id.list);
    }


    /**
     * 获取聊天好友列表
     */
    private  void getChatFriends() {
        String url = "http://jiekou.hydgyx.com/api/interface_chatfriends.php";
       cid= PreferencesUtils.getString(getActivity(), "cid");
        RequestParams params = new RequestParams();
        params.addBodyParameter("cid", cid);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        mLog.e(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("获取聊天好友列表：响应=" + XHttpUtils.Unicode2Chinese(responseInfo.result));
                        String result = XHttpUtils.Unicode2Chinese(responseInfo.result);
                        onGetChatFriends(result);
                    }

                    @Override
                    public void onStart() {
                        mLog.e("开始请求：");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("请求故障：" + msg);
                    }
                }
        );


    }


    /**
     * 获取聊天好友列表-响应值处理
     *
     * @param json
     */
    private void onGetChatFriends(String json) {
//        mLog.e("m2的json:" + json);
        if (!json.equals("")) {
            datas = new Gson().fromJson(json, new TypeToken<ArrayList<getChatFriendsResponse>>() {
            }.getType());

            if (!datas.isEmpty()) {
                mMailAdapter.setData(datas);
                setMailNumber();
                mMailAdapter.notifyDataSetChanged();
            }
        }

    }


    private void initContent() {
        mMailAdapter = new MailAdapter(getActivity());
        list.setAdapter(mMailAdapter);
        list.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            mLog.e("进入最近访问我的");
            String cid=PreferencesUtils.getString(getActivity(),"cid");
            PreferencesUtils.putInt(getActivity(), cid + "Fangke", 0);

//            AbToastUtil.showToast(getActivity(),"最近访问我正在开发中……");
            Intent intent = new Intent(getActivity(), B3_fangkeActivity.class);
            startActivity(intent);

        } else if (position == 1) {
            mLog.e("进入谁关注我");
//            AbToastUtil.showToast(getActivity(),"谁关注我正在开发中……");

            Intent intent2 = new Intent(getActivity(), B2_fensiActivity.class);
            startActivity(intent2);
        }  else if (position == 2) {
            mLog.e("进入聊过真心话的");

            String cid=PreferencesUtils.getString(getActivity(),"cid");
            PreferencesUtils.putInt(getActivity(), cid + "ZhenxinhuaFriend", 0);

//            AbToastUtil.showToast(getActivity(), "聊过真心话的列表正在开发中……");

            Intent intent = new Intent(getActivity(), B3_zhenxinhuaFriendActivity.class);
            startActivity(intent);

//            Intent intent2 = new Intent(getActivity(), B2_fensiActivity.class);
//            startActivity(intent2);
        } else if (position ==3) {
            mLog.e("进入缘分小秘书");
            PreferencesUtils.putInt(getActivity(),  "MishuMsg", 0);

//            AbToastUtil.showToast(getActivity(), "聊过真心话的列表正在开发中……");

            Intent intent = new Intent(getActivity(), C2_ServiceMsgActivity.class);
            startActivity(intent);

//            Intent intent2 = new Intent(getActivity(), B2_fensiActivity.class);
//            startActivity(intent2);
        }else {
            mLog.e("进入具体的聊天界面");
//            Intent it = new Intent().setClass(getActivity(), C1_LiaotianJiemianTestActivity.class);
//            it.putExtra("id", datas.get(position - 2).getId());
//            it.putExtra("name", datas.get(position - 2).getName());
//            it.putExtra("icon", datas.get(position - 2).getIcon());
//            it.putExtra("qianming", datas.get(position - 2).getQianming());
//            it.putExtra("flag", "1");
//            startActivity(it);

            //前面的图标个数
            int qian=4;
            PreferencesUtils.putInt(getActivity(),datas.get(position -qian).getId()+"MailNumber",0);
            Intent it = new Intent().setClass(getActivity(), C2_MsgActivity.class);
            it.putExtra("jid", datas.get(position -qian).getId());
            it.putExtra("jname", datas.get(position -qian).getName());
            it.putExtra("jicon", datas.get(position -qian).getIcon());
            it.putExtra("qianming", datas.get(position -qian).getQianming());
            it.putExtra("flag", "1");
            startActivity(it);

        }


    }


    /**
     * 下拉刷新：START*
     */

    private AbPullToRefreshView mAbPullToRefreshView = null;

    private void initPullToRefresh() {


        mAbPullToRefreshView = (AbPullToRefreshView) mainView.findViewById(R.id.root);

        // 设置监听器
        mAbPullToRefreshView.setOnHeaderRefreshListener(new AbPullToRefreshView.OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(AbPullToRefreshView abPullToRefreshView) {
                refreshTask();

            }
        });
        mAbPullToRefreshView.setOnFooterLoadListener(new AbPullToRefreshView.OnFooterLoadListener() {
            @Override
            public void onFooterLoad(AbPullToRefreshView abPullToRefreshView) {
                loadMoreTask();
            }
        });

        // 设置进度条的样式
        mAbPullToRefreshView.getHeaderView().setHeaderProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));
        mAbPullToRefreshView.getFooterView().setFooterProgressBarDrawable(
                this.getResources().getDrawable(R.drawable.progress_circular));

    }


    public void refreshTask() {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                AbDialogUtil.removeDialog(getActivity());
//                Toast.makeText(getActivity(),"执行刷新方法:"+"+"+new Random().nextInt(100),Toast.LENGTH_SHORT).show();

                getChatFriends();
                mAbPullToRefreshView.onHeaderRefreshFinish();
            }

            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }

            ;
        });

        mAbTask.execute(item);
    }

    public void loadMoreTask() {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                AbDialogUtil.removeDialog(getActivity());
//                Toast.makeText(getActivity(),"执行加载更多方法:"+"+"+new Random().nextInt(100),Toast.LENGTH_SHORT).show();
                mAbPullToRefreshView.onFooterLoadFinish();
            }

            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }

            ;
        });

        mAbTask.execute(item);
    }

    /**下拉刷新：END**/


}